import 'package:abc/controller/account_recovery_controller.dart';
import 'package:abc/controller/change_password_controller.dart';
import 'package:abc/controller/coin_recharge_controller.dart';
import 'package:abc/controller/profile_controller.dart';
import 'package:abc/controller/redeem_controller.dart';
import 'package:abc/controller/settings_controller.dart';
import 'package:abc/controller/share_promotion_controller.dart';
import 'package:abc/controller/vip_center_controller.dart';
import 'package:abc/page/account_recovery_page.dart';
import 'package:abc/page/change_password_page.dart';
import 'package:abc/page/coin_recharge_page.dart';
import 'package:abc/page/follow_page.dart';
import 'package:abc/page/my_likes_page.dart';
import 'package:abc/page/my_posts_page.dart';
import 'package:abc/page/point_task_page.dart';
import 'package:abc/page/profile_page.dart';
import 'package:abc/page/redeem_page.dart';
import 'package:abc/page/settings_page.dart';
import 'package:abc/page/share_promotion_page.dart';
import 'package:abc/page/vip_center_page.dart';
import 'package:abc/page/watch_history_page.dart'; // 添加播放历史页面导入
import 'package:abc/view/CustomActionCard.dart';
import 'package:abc/view/CustomActionInputField.dart';
import 'package:abc/view/CustomAppBar.dart';
import 'package:abc/view/CustomInputField.dart';
import 'package:abc/view/GradientButton.dart';
import 'package:abc/view/KeyboardAwareBottomSheet.dart';
import 'package:abc/view/PaymentMethodSheet.dart';
import 'package:abc/viewmodel/my_page_viewmodel.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';


class MyPage extends GetView<MyPageViewModel> {
  const MyPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 整体深色背景
    return Scaffold(
      backgroundColor: const Color(0xFF0E0F26), // 深色背景 (类似截图中的底色)
      body: Stack(
        children: [
          // 底部导航栏会被 Scaffold 自动处理，这里只关注内容区域
          CustomScrollView(
            slivers: [
              //顶部用户信息的渐变背景区域
              SliverToBoxAdapter(
                child: _buildHeaderSection(context),
              ),

              // 下半部分卡片和服务列表
              SliverPadding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                sliver: SliverList(
                  delegate: SliverChildListDelegate(
                    [
                      // VIP会员中心 (黑色卡片)
                      const SizedBox(height: 12),

                      //  金币充值/签到奖励 (左右卡片)

                      _buildTopServicesRow(),

                      // 广告横幅
                      const SizedBox(height: 20),
                      InkWell(child: _buildBannerAd(),onTap: () {
                        controller.showBottomUnlockSheet(context: context);
                      },),

                      // 更多服务模块
                      const SizedBox(height: 20),
                      _buildMoreServicesGrid(context),

                      // 其他服务模块
                      const SizedBox(height: 20), // 恢复为原来的10像素间距
                      _buildOtherServicesGrid(context),

                      const SizedBox(height: 40),
                    ],
                  ),
                ),
              ),
            ],
          ),

          // 顶部状态栏和设置按钮
          Positioned(
            top: 40,
            right: 16,
            child: GestureDetector(
              onTap: () {
                Get.to(() => const SettingsPage());
              },
              child: Image.asset(
                'assets/images/ic_setting.png',
                width: 24,
                height: 24,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // --- 1. 顶部用户信息和渐变背景 ---
  Widget _buildHeaderSection(BuildContext context) {
    return Container(
      height: 295 + 10,
      child: Stack(
        children: [
          Image.asset(
            'assets/images/my_top_bg.png',
            height: double.infinity,
          ),
          Container(
            height: 295 + 10,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 67),
                // 用户头像、昵称、ID、简介
                _buildUserInfo(),
                const SizedBox(height: 13),

                // 统计数据 (喜欢、帖子、关注、粉丝)
                _buildUserStatsRow(),
                Expanded(child: Container()),

                // VIP会员中心
                _buildVipMembershipCard()
              ],
            ).paddingSymmetric(horizontal: 15),
          )
        ],
      ),
    );
  }

  // --- 用户头像和信息 ---
  Widget _buildUserInfo() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 左侧头像和等级
        Stack(
          children: [
            Image.asset(
              'assets/images/default_avatar.png',
              width: 74,
              height: 74,
            ).paddingOnly(bottom: 6),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Image.asset(
                'assets/images/vip_1.png',
                width: 30,
                height: 15,
              ),
            ),
          ],
        ),
        const SizedBox(width: 12),

        // 昵称和简介
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  const Text(
                    '张大美丽',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        height: 1,
                        fontWeight: FontWeight.w500),
                  ),
                  const SizedBox(width: 6),
                  // VIP标签
                  Image.asset(
                    'assets/images/vip.png',
                    width: 30,
                    height: 15,
                  ),
                ],
              ),
              const SizedBox(height: 5),
              const Text(
                'ID: 123456',
                style: TextStyle(
                    color: Color(0xCCFFFFFF),
                    fontSize: 12,
                    height: 1,
                    fontWeight: FontWeight.w400),
              ),
              const SizedBox(height: 5),
              const Text(
                '这个人很懒，什么都没有留下~',
                style: TextStyle(
                    color: Color(0xCCFFFFFF),
                    fontSize: 12,
                    height: 1,
                    fontWeight: FontWeight.w400),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // --- 用户统计数据行 ---
  Widget _buildUserStatsRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
            flex: 1, // flex默认值为1，可省略
            child: _StatItem(count: '27', label: '喜欢')),
        Expanded(
            flex: 1, // flex默认值为1，可省略
            child: GestureDetector(
              onTap: () {
                // 跳转到我的帖子页面
                Get.to(() => const MyPostsPage());
              },
              child: _StatItem(count: '27', label: '我的帖子'),
            )),
        Expanded(
            flex: 1, // flex默认值为1，可省略
            child: GestureDetector(
              onTap: () {
                // 跳转到关注列表页面
                Get.to(() => const FollowPage(), arguments: 'follow');
              },
              child: _StatItem(count: '27', label: '关注'),
            )),
        Expanded(
            flex: 1, // flex默认值为1，可省略
            child: GestureDetector(
              onTap: () {
                // 跳转到粉丝列表页面
                Get.to(() => const FollowPage(), arguments: 'fans');
              },
              child: _StatItem(count: '27', label: '粉丝'),
            )),
      ],
    );
  }

  // --- 2. VIP会员卡片 ---
  Widget _buildVipMembershipCard() {
    return Container(
      height: 69,
      //  padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/open_vip_bg.png'),
          fit: BoxFit.contain, // 图片自适应容器，不裁剪（可能有空白）
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Image.asset(
            'assets/images/ic_crown.png',
            width: 22,
            height: 22,
          ),
          const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(height: 7),
              Text(
                'VIP会员中心',
                style: TextStyle(
                    color: Color(0xFF733300),
                    fontSize: 15,
                    fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 2),
              Text(
                '限时特惠，尊享会员权益',
                style: TextStyle(color: Color(0x80733300), fontSize: 13),
              ),
            ],
          ),
          GestureDetector(
            onTap: () {
              Get.to(() => const VipCenterPage());
            },
            child: Image.asset(
              'assets/images/activate_now.png',
              width: 79,
              height: 28,
            ),
          ),
        ],
      ).paddingSymmetric(horizontal: 17),
    );
  }

  // --- 3. 金币充值 / 签到奖励 / 分享推广 ---
  Widget _buildTopServicesRow() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 金币充值
        Expanded(
          flex: 1,
          child: _buildCoinRechargeCard(),
        ),
        const SizedBox(width: 6),
        // 签到奖励 + 分享推广
        Expanded(
          flex: 1,
          child: Column(
            children: [
              _buildSignServiceCard('签到领奖励', '立即签到', const Color(0xFFF79256)),
              const SizedBox(height: 12),
              GestureDetector(
                onTap: () {
                  Get.to(() => const SharePromotionPage());
                },
                child: _buildShareServiceCard(
                    '分享推广', '邀请好友领豪礼~', const Color(0xFFEA5455)),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // --- 4. 广告横幅 ---
  Widget _buildBannerAd() {
    return Container(
      height: 198,
      child: Image.asset('assets/images/banner.png'),
    );
  }

  // --- 5. 更多服务
  Widget _buildServicesGridItem(
      String title, List<Map<String, dynamic>> services, BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: const Color(0x33959595), // 卡片背景色
            borderRadius: BorderRadius.circular(10),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold),
              ).paddingOnly(bottom: 10),
              GridView.builder(
                padding: EdgeInsets.all(0),
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: services.length,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 5, // 每行5个图标
                  childAspectRatio: 1.0,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () {
                      _handleServiceItemClick(services[index]['label'] as String, context);
                    },
                    child: _ServiceGridItem(
                      path: services[index]['icon'] as String,
                      label: services[index]['label'] as String,
                    ),
                  );
                },
              )
            ],
          ),
        ),
      ],
    );
  }

  // --- 6.  其他服务 ---
  Widget _buildOtherServicesGridItem(
      String title, List<Map<String, dynamic>> services, BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: const Color(0x33959595), // 卡片背景色
            borderRadius: BorderRadius.circular(10),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold),
              ).paddingOnly(bottom: 10),
              GridView.builder(
                padding: EdgeInsets.all(0),
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: services.length,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, // 每行5个图标
                  childAspectRatio: 1.0,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () {
                      _handleServiceItemClick(services[index]['label'] as String, context);
                    },
                    child: _ServiceOtherGridItem(
                      path: services[index]['icon'] as String,
                      label: services[index]['label'] as String,
                    ),
                  );
                },
              )
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMoreServicesGrid(BuildContext context) {
    final services = [
      {'icon': 'ic_jbrw.png', 'label': '金币人物'},
      {'icon': 'ic_lsjl.png', 'label': '历史记录'},
      {'icon': 'ic_wdxh.png', 'label': '我的喜欢'},
      {'icon': 'ic_wdgm.png', 'label': '我的购买'},
      {'icon': 'ic_wdtz.png', 'label': '我的帖子'},
      {'icon': 'ic_dhm.png', 'label': '兑换码'},
      {'icon': 'ic_zhpz.png', 'label': '账号凭证'},
    ];
    return _buildServicesGridItem('更多服务', services, context);
  }

  Widget _buildOtherServicesGrid(BuildContext context) {
    final services = [
      {'icon': 'ic_bdyq.png', 'label': '绑定邀请'},
      {'icon': 'ic_gfqz.png', 'label': '官方群组'},
      {'icon': 'ic_swhz.png', 'label': '商务合作'},
      {'icon': 'ic_gfkf.png', 'label': '官方客服'},
    ];
    return _buildOtherServicesGridItem('其他服务', services, context);
  }

  // --- 金币充值卡片 ---
  Widget _buildCoinRechargeCard() {
    return Container(
      height: 154,
      child: Stack(
        children: [
          Image.asset(
            'assets/images/orange_bg.png',
            height: double.infinity,
            width: double.infinity,
            fit: BoxFit.fill,
          ),
          Row(
            children: [
              Column(
                children: [
                  const Text('金币充值',
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 15,
                          color: Color(0xFF95673A))),
                  const Text('余额：0',
                      style: TextStyle(fontSize: 13, color: Color(0xFF999999))),
                ],
              ).paddingOnly(top: 10, left: 12),
              Expanded(child: Container()),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  const Text('去充值',
                          style:
                              TextStyle(fontSize: 13, color: Color(0xFF999999)))
                      .paddingOnly(top: 12, right: 14),
                  Image.asset(
                    'assets/images/arrow_right.png',
                    height: 24,
                    width: 24,
                  ),
                ],
              )
            ],
          ),
          Positioned(
              bottom: 0,
              right: 0,
              child: Image.asset(
                'assets/images/orange_bottom_bg.png',
                width: 167,
                height: 154,
              ))
        ],
      ),
    );
  }

  // --- 签到小卡片 ---
  Widget _buildSignServiceCard(String title, String subtitle, Color color) {
    return Container(
      height: 71,
      child: Stack(
        children: [
          Image.asset(
            'assets/images/blue_bg.png',
            height: double.infinity,
            width: double.infinity,
            fit: BoxFit.fill,
          ),
          Positioned(
              bottom: 0,
              right: 0,
              child: Image.asset(
                'assets/images/blue_bottom_bg.png',
                width: 68,
                height: 68,
              )),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('签到领奖励',
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 15,
                      color: Color(0xFF386480))),
              const Text('立即签到~',
                  style: TextStyle(fontSize: 13, color: Color(0xFFA5A8AA))),
            ],
          ).paddingOnly(top: 10, left: 12),
        ],
      ),
    );
  }

  // --- 分享小卡片 ---
  Widget _buildShareServiceCard(String title, String subtitle, Color color) {
    return Container(
      height: 71,
      child: Stack(
        children: [
          Image.asset(
            'assets/images/pink_bg.png',
            height: double.infinity,
            width: double.infinity,
            fit: BoxFit.fill,
          ),
          Positioned(
              bottom: 0,
              right: 0,
              child: Image.asset(
                'assets/images/pink_bottom_bg.png',
                width: 68,
                height: 68,
              )),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('分享推广',
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 15,
                      color: Color(0xFF703140))),
              const Text('邀请好友领豪礼~',
                  style: TextStyle(fontSize: 13, color: Color(0xFFADA6A7))),
            ],
          ).paddingOnly(top: 10, left: 12),
        ],
      ),
    );
  }

  void _handleServiceItemClick(String label, BuildContext context) {
    switch (label) {
      case '金币人物':
        // 跳转到金币充值页面
        Get.to(() => const CoinRechargePage());
        break;
      case '历史记录':
        // 跳转到积分任务页面
        Get.to(() => const PointTaskPage());
        break;
      case '我的喜欢':
        // 跳转到我的喜欢页面
        Get.to(() => const MyLikesPage());
        break;
      case '我的购买':
        // TODO: 跳转到我的购买页面
        Get.snackbar('提示', '点击了我的购买');
        break;
      case '我的帖子':
        // TODO: 跳转到我的帖子页面
        Get.snackbar('提示', '点击了我的帖子');
        break;
      case '兑换码':
        controller.showRedeemCodeSheet(context);
        break;
      case '账号凭证':
        // TODO: 跳转到账号凭证页面
        Get.snackbar('提示', '点击了账号凭证');
        break;
      case '绑定邀请':
        // TODO: 跳转到绑定邀请页面
        controller.showInviteCodeSheet(context);
        break;
      case '官方群组':
        // TODO: 跳转到官方群组页面
       controller.showOfficialTeamGroupSheet(context);
        break;
      case '商务合作':
        // TODO: 跳转到商务合作页面
         controller.showBusinessCooperationSheet(context);
        break;
      case '官方客服':
        // TODO: 跳转到官方客服页面
        Get.snackbar('提示', '点击了官方客服');
        break;
      default:
        Get.snackbar('提示', '点击了 $label');
    }
  }

}

class _StatItem extends StatelessWidget {
  final String count;
  final String label;

  const _StatItem({required this.count, required this.label});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          count,
          style: const TextStyle(
              color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(color: Color(0x80FFFFFF), fontSize: 13),
        ),
      ],
    ).paddingSymmetric(vertical: 10);
  }
}

class _ServiceGridItem extends StatelessWidget {
  final String path;
  final String label;

  const _ServiceGridItem({required this.path, required this.label});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset(
          'assets/images/${path}',
          width: 20,
          height: 20,
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(color: Colors.white, fontSize: 12),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }
}

class _ServiceOtherGridItem extends StatelessWidget {
  final String path;
  final String label;

  const _ServiceOtherGridItem({required this.path, required this.label});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(
              child: Image.asset(
                'assets/images/${path}',
                width: 32,
                height: 32,
              ),
            )),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(color: Colors.white, fontSize: 12),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }
}
